package com.hna.eking.AirlineServer.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.hna.eking.AirlineServer.Exception.RunServiceException;
import com.hna.eking.AirlineServer.Mapper.AirportInfoMapper;
import com.hna.eking.AirlineServer.Mapper.AreaMapInfo;
import com.hna.eking.AirlineServer.Mapper.AreaMapInfoMapper;
import com.hna.eking.AirlineServer.Mapper.MapInfo;
import com.hna.eking.AirlineServer.Mapper.MapInfoMapper;
import com.hna.eking.AirlineServer.Utils.FileUtils;

/**
 *
 * 区域表的控制类 Date : 2018-9-19 
 * Description: 区域表的控制类 
 * Copyright: Copyright &copy 2018 
 * Company :aivac
 * 
 * @author APP BD lele
 * @version V1.0
 *  修改历史 序号 日期 修改人 修改原因 1
 * 
 */
@Service
public class AreaMapService {
	@Autowired
	AreaMapInfoMapper mapper;
	private Logger logger = LoggerFactory.getLogger(AreaMapService.class);
	@Autowired
	private FileUtils fileServ;
	@Autowired
	MapInfoMapper mapMapper;
	@Autowired
	AirportInfoMapper airportMapper;
	@Value("${visualcharts.state.area}")
	private String AREA_TYPE;
	@Value("${visualcharts.state.enable}")
	private String ROW_STAT_ENABLE;
	@Autowired
	MapInfoService mapServ;
	
	/*
	 * 新增区域图信息 
	 * 参数： 区域图信息：AreaMapInfo
	 * 
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  void InsertAreaMap(AreaMapInfo areaMapInfo, MultipartFile file) {
		String fileName = null;
		try {
			
			Date SysDate = new Date();			
			String User = areaMapInfo.getCreateUser();
			
			 /*如果文件不为空 则上传新航图*/
			if(file == null) {
				logger.error("update file is null");
				throw new RunServiceException(RunServiceException.FILE_UPLOAD_NULL);
			}			
			
			/* 新增用户不能为空，否则失败 */
			if (User == null || "".equals(User)) {
				logger.error("update user can not be null");
				throw new RunServiceException(RunServiceException.UNKONW_USER);
			}
			
//			logger.debug("lele 测试" + ROW_STAT_ENABLE + AREA_TYPE);
			/*上传区域图，不需要机场代码 只将文件上传到common目录*/
			fileName = fileServ.GenUploadFileName(null, AREA_TYPE, file.getOriginalFilename());
			fileServ.UploadFile(fileName, file);
			   
			/* 插入区域图信息*/			
			areaMapInfo.setCreateDate(SysDate);
			areaMapInfo.setUpdateDate(SysDate);
			areaMapInfo.setCreateUser(User);
			areaMapInfo.setUpdateUser(User);
			areaMapInfo.setEffectFlag(ROW_STAT_ENABLE);
			areaMapInfo.setFilePath(fileName);
			mapper.InsertAreaInfo(areaMapInfo);
		} catch(DuplicateKeyException ex) {
			logger.error("unique error");
			ex.printStackTrace();
			throw new RunServiceException(RunServiceException.UNIQUE_ERROR);
		}catch (DataAccessException e) {
			logger.error("database error");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		}catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block		
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.FILE_UPLOAD_FAIL);
		}
	}
	
	/*
	 * 更新区域图信息 
	 * 参数： 区域图信息：AreaMapInfo
	 * 
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  void UpdateAreaMap(AreaMapInfo areaMapInfo, MultipartFile file) {
		String fileName = null;
		try {
			
			Date SysDate = new Date();			
			String User = areaMapInfo.getUpdateUser();
			
			/* 更新用户不能为空，否则失败 */
			if (User == null || "".equals(User)) {
				logger.error("update user can not be null");
				throw new RunServiceException(RunServiceException.UNKONW_USER);
			}
			
			AreaMapInfo orgInfo = mapper.selectByCode(areaMapInfo.getMapCode());
			if(orgInfo == null) {
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND, "get area map by code not found");
			}
			 /*如果文件不为空 则上传新航图*/
			if(file != null) {
				/*生成区域图，不需要机场代码 只将文件上传到common目录*/
				fileName = fileServ.GenUploadFileName(null, AREA_TYPE, file.getOriginalFilename());
				areaMapInfo.setFilePath(fileName);
			}else {
				areaMapInfo.setFilePath(orgInfo.getFilePath());
			}
			
			/* 更新区域图信息*/
			areaMapInfo.setUpdateDate(SysDate);
			areaMapInfo.setUpdateUser(User);
			mapper.UptAreaInfo(areaMapInfo);
			
			/*查询所有航图表该区域图的航图*/
			List<MapInfo> mapinfo = mapMapper.selectByPrimaryKey(areaMapInfo.getMapCode());
			
			/*更新所有机场的区域图的信息*/			
			for(MapInfo tempMap : mapinfo) {
				tempMap.setMapName(areaMapInfo.getMapName());
				tempMap.setFilePath(areaMapInfo.getFilePath());
				tempMap.setUpdateUser(User);				
				//mapMapper.UpdateMapInfo(tempMap);
//				logger.debug("lele--->>>>>" + areaMapInfo.getFilePath() + tempMap.getFilePath());
				mapServ.MapInfoUpdate(tempMap);
			}
			
			if(file != null) {
				/*上传区域图，*/
				fileServ.UploadFile(fileName, file);
				/*删除旧航图*/
				fileServ.delete(orgInfo.getFilePath());
			}	
		}catch(DuplicateKeyException ex) {
			logger.error("unique error");
			ex.printStackTrace();
			throw new RunServiceException(RunServiceException.UNIQUE_ERROR);
		}catch (DataAccessException e) {
			logger.error("database error");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		}catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block		
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.FILE_UPLOAD_FAIL);
		}
	}
	
	/*
	 * 删除区域图 
	 * 参数： 区域图信息：AreaMapInfo
	 * 
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  void DeleteAreaMap(String mapCode, String User) {
		try {
			
			Date SysDate = new Date();				
			
			/* 更新用户不能为空，否则失败 */
			if (User == null || "".equals(User)) {
				logger.error("update user can not be null");
				throw new RunServiceException(RunServiceException.UNKONW_USER);
			}
			
			/*查询要删除的信息*/
			AreaMapInfo info = mapper.selectByCode(mapCode);
			if(info == null) {
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND);
			}
			/* 删除区域图信息*/;
			mapper.DelAreaInfo(mapCode, User, SysDate);
			
			/*查询所有航图表该区域图的航图*/
			List<MapInfo> mapinfo = mapMapper.selectByPrimaryKey(mapCode);
			
			/*更新所有机场的区域图的信息*/			
			for(MapInfo tempMap : mapinfo) {
				mapServ.DeleteMapInfo(tempMap.getAirportCode(), mapCode, User, false);
			}
			
			/*删除文件*/
			fileServ.delete(info.getFilePath());
		} catch (DataAccessException e) {
			logger.error("database error");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		}
	}
	
	/*
	 * 查询指定记录数区域图 
	 * 参数： 区域图信息：AreaMapInfo
	 * 
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  Map<String, Object> SeleteAreaMap(String mapCode, String mapName, int limit, int offset) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			/* 查询所有记录条数 */
			int Count = mapper.selectCountByInput(mapCode, mapName);
			if (Count == 0) {
				logger.warn("select airport info row is 0");
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND);
			}

			/* 查询机场信息 */
			List<AreaMapInfo> list = mapper.selectAllByInput(mapCode, mapName, limit, offset);
			if(list == null || list.size() == 0) {
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND);
			}
			map.put("count", Count);
			map.put("maplist", list);
			return map;
		}catch (DataAccessException e) {
			logger.error("DATABASE ERROR");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		} 
	
	}
	
	/*
	 * 查询所有记录数区域图 
	 * 参数： 区域图信息：AreaMapInfo
	 * 
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  List<AreaMapInfo> SeleteAll() {
		try {
			/* 查询机场信息 */
			List<AreaMapInfo> list = mapper.selectAllEfft();
			if(list == null || list.size() == 0) {
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND);
			}
			return list;
		}catch (DataAccessException e) {
			logger.error("DATABASE ERROR");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		} 
	
	}
	
	/*
	 * 新增区域图到航图表 
	 * 参数： 
	 * 机场代码：airportCode
	 * 区域图代码：mapCode
	 * 插入用户 User
	 * 返回： 无
	 *
	 */
	@Transactional(rollbackFor = RunServiceException.class)
	public  void addAreaMap(String airportCode, String mapCode, String User) {
		try {
			Date sysDate = new Date();
			if(User == null || "".equals(User)) {
				throw new RunServiceException(RunServiceException.UNKONW_USER);
			}
			/* 查询区域图信息 */
			AreaMapInfo info = mapper.selectByCode(mapCode);
			if(info == null ) {
				throw new RunServiceException(RunServiceException.DATA_NOT_FOUND);
			}
			
			MapInfo map = mapMapper.selectByAirportcodeAndMapcode2(airportCode, mapCode);
			if (map != null) {
				/* 将区域图的生效标志恢复，并将必要字段重新赋值（踩坑了）*/
				map.setEffectFlag("0001");
				map.setMapName(info.getMapName());
				map.setFilePath(info.getFilePath());
				map.setUpdateDate(sysDate);
				map.setUpdateUser(User);
				mapMapper.UpdateMapInfo(map);
				airportMapper.updateAirportMapVersion(airportCode, sysDate, User);
			} else {
				/*插入区域图到航图信息表*/
				MapInfo mapinfo = new MapInfo();
				mapinfo.setAirportCode(airportCode);
				mapinfo.setMapCode(mapCode);
				mapinfo.setMapName(info.getMapName());
				mapinfo.setFilePath(info.getFilePath());
				mapinfo.setCreateDate(sysDate);
				mapinfo.setUpdateDate(sysDate);
				mapinfo.setCreateUser(User);
				mapinfo.setUpdateUser(User);
				mapinfo.setMapType(this.AREA_TYPE);
				
				this.mapServ.MapInfoInsert(mapinfo);
			}
			
		}catch (DataAccessException e) {
			logger.error("DATABASE ERROR");
			e.printStackTrace();
			throw new RunServiceException(RunServiceException.DATABASE_ERROR);
		} 
	
	}
}
